//
//  MainViewController.swift
//  SinaMicroBlog
//
//  Created by long108 on 15/12/4.
//  Copyright © 2015年 long108. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    /// 中间➕按钮懒加载
    
    lazy var composeBtn: UIButton = UIButton(
        imageName: "tabbar_compose_icon_add",
        backgroundImageName: "tabbar_compose_button")
    
    /// ➕按钮点击调用的方法
    @objc private func clickComposedBtn(){
        print("点我了")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //
       
        
        
        // 添加子控制器
        addChildViewControllers()
        // 设置tabBar渲染颜色
        tabBar.tintColor = UIColor.orangeColor()
        
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // 确保tabBar出来以后再添加按钮
        // 如果在ViewDidLoad中添加按钮, 按钮会添加在tabBar的下面
        setupComposedBtn()
    }
    
}

// MARK: 设置界面
extension MainViewController{
    // 添加➕按钮
    private func setupComposedBtn(){
        // 添加按钮
        tabBar.addSubview(composeBtn)
        
        //调整按钮的frame
        // 子控制器的个数
        let count = childViewControllers.count
        
        let w = tabBar.bounds.width/CGFloat(count) - 1
//        composeBtn.frame = CGRectMake(2*w, 0, w, tabBar.bounds.height)
        
        composeBtn.frame = CGRectInset(tabBar.bounds, 2*w, 0)
        
        composeBtn.addTarget(self, action: "clickComposedBtn", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    // 添加所有子控制器
    private func addChildViewControllers() {
        //
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        // 占位控制器
        addChildViewController(UIViewController())
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
        
    }
    
    // 添加子控制器重载方法
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        // 设置标题
        vc.title = title
        // 设置tabBar的图片
        vc.tabBarItem.image = UIImage(named: imageName)
        // 让控制器成为navVC的根控制器
        let navVC = UINavigationController(rootViewController: vc)
        // 将navVC设置为tabBarVC的子控制器
        addChildViewController(navVC)
    }
}